Skip to content

Instantly share code, notes, and snippets.

@lindexi
Created May 22, 2018 06:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lindexi/36c5e223ff77cfb8adc4909dec1576b5 to your computer and use it in GitHub Desktop.
Save lindexi/36c5e223ff77cfb8adc4909dec1576b5 to your computer and use it in GitHub Desktop.
uwp string to color
public SolidColorBrush GetSolidColorBrush(string hex)
{
hex = hex.Replace("#", string.Empty);
//#FFDFD991
//#DFD991
//#FD92
//#DAC
bool existAlpha = hex.Length == 8 || hex.Length == 4;
bool isDoubleHex = hex.Length == 8 || hex.Length == 6;
if (!existAlpha && hex.Length != 6 && hex.Length != 3)
{
throw new ArgumentException("Input string is invalid color");
}
int n = 0;
byte a;
int hexCount = isDoubleHex ? 2 : 1;
if (existAlpha)
{
n = hexCount;
a = (byte) ConvertHexToByte(hex, 0, hexCount);
if (!isDoubleHex)
{
a = (byte) (a * 16 + a);
}
}
else
{
a = 0xFF;
}
var r = (byte) ConvertHexToByte(hex, n, hexCount);
var g = (byte) ConvertHexToByte(hex, n + hexCount, hexCount);
var b = (byte) ConvertHexToByte(hex, n + 2 * hexCount, hexCount);
if (!isDoubleHex)
{
//#FD92 = #FFDD9922
r = (byte) (r * 16 + r);
g = (byte) (g * 16 + g);
b = (byte) (b * 16 + b);
}
return new SolidColorBrush(Windows.UI.Color.FromArgb(a, r, g, b));
}
private static uint ConvertHexToByte(string hex, int n, int count = 2)
{
return Convert.ToUInt32(hex.Substring(n, count), 16);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment